#pragma once

#include "znx_syscall.h"
#include "znx_string.h"

static inline int64_t
znx_read_file(const char *file, u_char *buf,
    size_t buf_size, char **err)
{
    int                         fd;
    znx_syscall_result_t        sres;
    znx_file_stat_t             stat;
    size_t                      file_size;

    sres = znx_syscall_open_nomode(file, O_RDONLY);
    if (sres.eno != 0) {
        *err = strerror((int)sres.eno);
        return -1;
    }

    fd = (int)sres.res;

    sres = znx_syscall_file_fstat(fd, &stat);
    if (sres.eno != 0) {
        *err = strerror((int)sres.eno);
        goto failed;
    }

    file_size = (size_t)stat.st_size;
    if (buf_size < file_size) {
        *err = "buf size is too small";
        goto failed;
    }

    sres = znx_syscall_read(fd, buf, file_size);
    if (sres.eno != 0) {
        *err = strerror((int)sres.eno);
        goto failed;
    }

    return sres.res;

failed:
    znx_syscall_close(fd);
    return -1;
}